﻿using System.Drawing;
using System.Windows.Forms;

namespace CloudShot.Forms
{
  public class MoveableForm : Form
  {
    private Control _dragControl;
    private bool _drag;
    private Point _startPoint = new Point(0, 0);

    protected Control DragControl
    {
      get { return _dragControl; }
      set
      {
        Unsubscribe(_dragControl);
        _dragControl = value;
        Subscribe(_dragControl);
      }
    }

    private void Subscribe(Control dragControl)
    {
      if (dragControl == null)
        return;

      dragControl.MouseDown += OnControlMouseDown;
      dragControl.MouseMove += OnControlMouseMove;
      dragControl.MouseUp += OnControlMouseUp;
    }

    private void Unsubscribe(Control dragControl)
    {
      if (dragControl == null)
        return;

      dragControl.MouseDown -= OnControlMouseDown;
      dragControl.MouseMove -= OnControlMouseMove;
      dragControl.MouseUp -= OnControlMouseUp;
    }

    #region Event Handlers

    private void OnControlMouseDown(object sender, MouseEventArgs e)
    {
      _drag = true;
      _startPoint = new Point(e.X, e.Y);
    }

    private void OnControlMouseMove(object sender, MouseEventArgs e)
    {
      if (!_drag)
        return;

      Point screenMousePosition = PointToScreen(e.Location);
      Location = new Point(screenMousePosition.X - _startPoint.X, screenMousePosition.Y - _startPoint.Y);
    }

    private void OnControlMouseUp(object sender, MouseEventArgs e)
    {
      _drag = false;
    }

    #endregion
  }
}